#Java - Code Snippets for '#String split' - 4 code snippet(s) found |
|
Sample 1. Get all words from a String and display them | |
|
String string = "I don't think we are in Kansas anymore";
String splittedString = str1.split(" ");
int count = 1;
for(String str: splittedString){
System.out.println("Word number:" + count + ":" + str);
count++;
}
|
|
Like Feedback string string split Get all words from a String word count |
|
|
Sample 2. Remove Alien characters i.e removing everything except characters , numbers and special characters. | |
|
String removeAlienCharacters(String str){
String newString = new String();
String returnString = "";
if(str.contains("<")){
String[] str2 = str.split("<");
str = str2[0];
}
for(char x: str.toCharArray()){
if((x >= 48 && x <= 57) || (x>=65 && x <= 90) || (x >= 97 && x<= 122) || x=='.'){
returnString += x;
}
}
return returnString.trim();
}
|
|
Like Feedback string .contains() .split() string split string contains remove characters from string remove alien characters |
|
|
Sample 3. Method to get a map of words and their count by passing in the string | |
|
Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}
countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());
for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}
|
|
Like Feedback map word count map of string and integer containsKey string split treeset Collections.reverseOrder set addAll entry |
|
|
Sample 4. Find shortest and longest word in a string | |
|
public static void main(String[] args) {
String str = "We are not in Kansas anymore";
String shortestWord = "";
String longestWord = "";
int shortestWordLength = 1000;
int longestWordLength = 0;
String[] splitStr = str.split(" ");
for(String string: splitStr){
if(string.length() > longestWordLength){
longestWord = string;
longestWordLength = string.length();
} else if(string.length() < shortestWordLength){
shortestWord = string;
shortestWordLength = string.length();
}
}
System.out.println("Shortest Word :" + shortestWord);
System.out.println("Longest Word :" + longestWord);
}
|
|
Like Feedback string string.split |
|
|